package com.dapeis.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import com.ag.core.exception.SysTipsException;
import com.ag.core.utils.AgAssert;
import com.ag.dao.DBService;
import com.ag.dao.IDao;
import com.ag.utils.NumberUtils;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.dao.IShopMapper;
import com.dapeis.domain.Order;
import com.dapeis.domain.Requirement;
import com.dapeis.domain.Shop;

@Service
public class ShopService extends DBService<Shop> {

    @Resource
    IShopMapper shopMapper;

    @Resource
    RequirementService requirementService;

    @Override
    protected IDao<Shop> getIDao() {
	return shopMapper;
    }

    public List<Shop> getShopByCollocationId(Integer collocationId) {
	Example example = new Example(Shop.class);
	Criteria criteria = example.createCriteria();
	criteria.andEqualTo(Shop.PROPERTY_COLLOCATIONID, collocationId);
	example.orderBy(Shop.PROPERTY_TYPE).desc();
	List<Shop> shops = selectByExample(example);
	return shops;
    }

    public boolean addOrUpdate(Shop shop) {
	if (null == getShop(shop.getType(), shop.getCollocationId())) {
	    return insertSelective(shop) > 0;
	} else {
	    return updateByPrimaryKeySelective(shop) > 0;
	}
    }

    public Shop getShop(Integer type, Integer collocationId) {
	Example example = new Example(Shop.class);
	Criteria criteria = example.createCriteria();
	criteria.andEqualTo(Shop.PROPERTY_COLLOCATIONID, collocationId);
	criteria.andEqualTo(Shop.PROPERTY_TYPE, type);
	Shop shop = selectOneByExample(example);
	return shop;
    }

    public boolean serverFinishAddNum(Order order) {
	if (order.getType().equalsIgnoreCase(
		StylistConstants.Order.Type.REQUIREMENT)) {
	    Requirement requirement = requirementService
		    .selectByPrimaryKey(order.getLinkId());
	    if (null != requirement
		    && NumberUtils.isValid(requirement.getShopId())) {
		Shop dbShop = selectByPrimaryKey(requirement.getShopId());
		dbShop.setBuyNum(dbShop.getBuyNum() + 1);
		return updateByPrimaryKeySelective(dbShop) > 0;
	    }
	}
	return false;
    }

    public Shop getSingleShop(Integer id, Integer type, Integer collocationId) {
	Shop shop = null;
	if (NumberUtils.isValid(id)) {
	    shop = selectByPrimaryKey(id);
	    AgAssert.notNull(shop, SysTipsException.class, "找到不到shop信息 id："
		    + id);
	}
	if (NumberUtils.isValid(type)) {
	    shop = getShop(type, collocationId);
	}
	return shop;
    }
}
